<?php
namespace Api\Provider\Admin;
use Api\Provider\IndexProvider;
use User\Api\UserApi;
use Think\Log;

/**
 * Description of ConstantProvider
 */

set_time_limit(0);
class DataTransferProvider extends IndexProvider
{
    
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 公共配置参数获取
     * @param $param
     */
    public function transfer($param)
    {
        //echo APP_PATH; exit;
        Log::writeInfo('start to execute transfer in DataTransferProvider, param:' .json_encode($param),'data_transfer');
       
        $dir = APP_PATH."db";
        $handler = opendir($dir);
        
        while( ($filename = readdir($handler)) !== false ) {
            //3、目录下都会有两个文件，名字为’.'和‘..’，不要对他们进行操作
            if($filename != "." && $filename != ".."){
                //4、进行处理
                //这里简单的用echo来输出文件名
                switch ($filename) {
                    //case "admins.json": $this->process_admin($dir.'/'.$filename);
                    //case "users.json": $this->process_user($dir.'/'.$filename);
                    //case "tags.json": $this->process_tag($dir.'/'.$filename);
                    //case "scores.json": $this->process_score($dir.'/'.$filename);
                    //case "lists.json": $this->process_list($dir.'/'.$filename);
                    case "freelists.json": $this->process_freelist($dir.'/'.$filename, 'ScoreFree');
                    case "hotlists.json": $this->process_freelist($dir.'/'.$filename, 'ScoreHot');
                    case "newlists.json": $this->process_freelist($dir.'/'.$filename, 'ScoreNew');
                    default: break;
                }
                
            }
        }
        
        //5、关闭目录
        closedir($handler);
        exit;
        
    }
    
    private function process_admin($filePath){
        $file = fopen($filePath, 'r');
        $data = array();
        while(!feof($file)) {
        
            $json = fgets($file);
            $obj = json_decode($json, true);
            //print_r($obj);
            if(empty($obj)) continue;
            $User   =   new UserApi;
            $uid    =   $User->register($obj['account'], $obj['pwd'], $obj['account'].'@dscore.com');
            if(0 < $uid){ //注册成功
                $user = array('uid' => $uid, 'nickname' => $obj['name'], 'status' => 1, 'oid'=>$obj['_id']['$oid']);
                M('Member')->add($user);
            } 
        }
        
        
        fclose($file);
    }
    
    private function process_favlist(){

        return;
    }
    
    private function process_freelist($filePath, $tableName){
        $file = fopen($filePath, 'r');
        $data = array();
        while(!feof($file)) {
            
            $json = fgets($file);
            $obj = json_decode($json, true);
            //print_r($obj);
            if(empty($obj)) continue;
            $data[] = array(
                'score_oid'  =>  $obj['id'],
                'create_time'  =>  date("Y-m-d H:i:s",strtotime($obj['create_date']['$date'])),
            );
        }

        $score_oids = array_unique(array_column($data, "score_oid"));
        $map['oid'] = array('in', $score_oids);
        $Model = M('Score');
        $scoreList = $Model->where($map)->select();   
        $scoreMap = array();
        foreach ($scoreList as $key=> $val) {
            $scoreMap[$val['oid']]  = $val['id'];
        }

       foreach ($data as $key => $val) {
           $data[$key]['score_id']  = $scoreMap[$val['score_oid']];
           unset($data[$key]['score_oid']);
       }
        //分批入库
        $Model = M($tableName);
        $count = count($data);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($data, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 50;
            echo $Model->getDbError();
        }
        fclose($file);
        return;
    }
    
    private function process_hotlist(){
        return;
    }
    
    private function process_list($filePath){
        $file = fopen($filePath, 'r');
        $data = array();
        
        $user = array();
        $admin = array();
        $images = array();
        $tags = array();
        $sheets = array();

        while(!feof($file)) {
            
            $json = fgets($file);
            $obj = json_decode($json, true);
            //print_r($obj);
            if(empty($obj)) continue;
            if($obj['author']['author_type'] == 'admin') {
                $admin[] = array(
                    'oid'   =>  $obj['_id']['$oid'],
                    'admin_id' => $obj['author']['id'],
                );
            } else {
                $user[] = array(
                    'oid'   =>  $obj['_id']['$oid'],
                    'user_id' => $obj['author']['id'],
                );
            }
            $data[] = array(
                'oid'  =>  $obj['_id']['$oid'],
                'name'  =>  $obj['name'],
                'is_private'  => $obj['is_private'] ? 1 : 0,
                'author_type'  => $obj['author']['author_type'] == 'admin' ? 10: 20,
                'create_time'  =>  date("Y-m-d H:i:s",strtotime($obj['create_date']['$date'])),
                'update_time'  =>  date("Y-m-d H:i:s",strtotime($obj['update_date']['$date'])),
                "author"=>$obj['author']
            );

            
            $pic =array(
                "pic"=>$obj['image'],
                "score_oid"  =>  $obj['_id']['$oid'],
                'author_type'  => $obj['author']['author_type'] == 'admin' ? 10: 20,
                "author"=>$obj['author']
            ) ;
            $picList[] = $pic;
            
            $tags[] = array(
                "tags"=>$obj['tags'],
                "score_oid"  =>  $obj['_id']['$oid'],
                'author_type'  => $obj['author']['author_type'] == 'admin' ? 10: 20,
                "author"=>$obj['author']
            );

            $sheets[] = array(
                "sheets"=>$obj['score'],
                "score_oid"  =>  $obj['_id']['$oid'],
                'author_type'  => $obj['author']['author_type'] == 'admin' ? 10: 20,
                "author"=>$obj['author']
            );
        }
        
        
        //获取admin 和user信息
        $admin_oids = array_unique(array_column($admin, "admin_id"));
        $map['oid'] = array('in', $admin_oids);
        $Model = M('Member');
        $adminList = $Model->where($map)->select();   
        $adminMap = array();
        foreach ($adminList as $key=> $val) {
            $adminMap[$val['oid']]  = $val['uid'];
        }

        unset($map);
        $user_oids = array_unique(array_column($user, "user_id"));
        if(!empty($user_oids)) {
            $map['oid'] = array('in', $user_oids);
            $userList = M('User')->where($map)->select();
            $userMap = array();
            foreach ($userList as $key=> $val) {
                $userMap[$val['oid']]  = $val['id'];
            }
        }


        foreach ($data as $key=>$sheet) {
            //admin
            if($sheet['author_type'] == 10) {
                $data[$key]['creator'] = $adminMap[$sheet['author']['id']];
            } else {
                $data[$key]['creator'] = isset($userMap) ? $userMap[$sheet['author']['id']] : 0;
            }
            unset($data[$key]['author']);
        }

        //分批添加曲谱
        $Model = M('Score');
        $count = count($data);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($data, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 50;
            echo $Model->getDbError();
        }
        
        
        //添加谱单图片信息
        foreach ($picList as $key=>$pic) {
            if($pic['author_type'] == 10) {
                $creator = $adminMap[$pic['author']['id']];
            } else {
                $creator = isset($userMap) ? $userMap[$pic['author']['id']] : 0;
            }
            foreach ($pic['pic'] as $key=>$val) {
                $images[] = array(
                    "name"  => $val['name'],
                    "url"  => $val['thumbUrl'],
                    "img_type"  => 20,
                    "creator"=>$creator,
                    "oid"   => $val['_id']['$oid']
                    
                );
            }
        }
        
        $Model = M('Image');
        $count = count($images);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($images, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 50;
            echo $Model->getDbError();
        }
        
        //图片和谱单的关系
        unset($map);
        $score_oids = array_column($picList, "score_oid");
        $map['oid'] = array('in', $score_oids);
        $scoreList = M('Score')->where($map)->select();
        
        foreach ($scoreList as $key=> $val) {
            $scoreMap[$val['oid']]  = $val['id'];
        }
        
        unset($map);
        $image_oids = array_column($images, "oid");
        $map['oid'] = array('in', $image_oids);
        $imageList = M('Image')->where($map)->select();
        foreach ($imageList as $key=> $val) {
            $imageMap[$val['oid']]  = $val['id'];
        }
        
        $image_sheet = array();
        foreach ($picList as $key=>$pic) {
            if($pic['author_type'] == 10) {
                $creator = $adminMap[$pic['author']['id']];
            } else {
                $creator = isset($userMap) ? $userMap[$pic['author']['id']] : 0;
            }
            foreach ($pic['pic'] as $key=>$val) {
                $image_sheet[] = array(
                    'score_id' => $scoreMap[$pic['score_oid']],
                    'image_id' => $imageMap[$val['_id']['$oid']],
                    'creator'  => $creator
                );
            }
            
        }
        

        $Model = M('ImageScore');
        $count = count($image_sheet);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($image_sheet, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 50;
            echo $Model->getDbError();
        }
        
        //添加谱曲标签信息
        unset($map);
         $tag_oids = array();
        foreach ($tags as $key => $tag) {
            $tag_oids =  array_merge($tag['tags'], $tag_oids);
            
        }
        
        if(!empty($tag_oids)) {
            $map['oid'] = array('in', array_unique($tag_oids));
            $Model = M('Tag');
            $tagsList = $Model->where($map)->select();
            foreach ($tagsList as $key=> $val) {
                $tagMap[$val['oid']]  = $val['id'];
            }

            $tagSheetList = array();
            foreach ($tags as $key=>$tag) {
                if($tag['author_type'] == 10) {
                    $creator = $adminMap[$tag['author']['id']];
                } else {
                    $creator = isset($userMap) ? $userMap[$tag['author']['id']] : 0;
                }
                foreach ($tag['tags'] as $key=>$val) {
                    $tagSheetList[] = array(
                        "tag_id"  => $tagMap[$val],
                        "score_id"  => $scoreMap[$tag['score_oid']],
                        "creator"=>$creator
                    );
                }
                
            }
            

            $Model = M('TagScore');
            $count = count($tagSheetList);
            $start = 0;
            while($start <= $count) {
                $slice_data = array_slice($tagSheetList, $start, 50);
                $rowCount = $Model->addAll($slice_data);
                $start += 50;
                echo $Model->getDbError();
            }
        }


        //添加谱单和曲谱关系
        unset($map);
        $sheet_oids = array();
        foreach ($sheets as $key => $sheet) {
             
            foreach ($sheet['sheets'] as $key => $val) {

                array_push($sheet_oids, $val['sid']);
                
            }

        }
               
        if(!empty($sheet_oids)) {
            $map['oid'] = array('in', array_unique($sheet_oids));
            $Model = M('Sheet');
            $sheetList = $Model->where($map)->select();

            if(!empty($sheetList)) {

                foreach ($sheetList as $key=> $val) {
                    $sheetMap[$val['oid']]  = $val['id'];
                }

                $scoreSheetList = array();
                foreach ($sheets as $key=>$sheet) {
                    if($sheet['author_type'] == 10) {
                        $creator = $adminMap[$sheet['author']['id']];
                    } else {
                        $creator = isset($userMap) ? $userMap[$sheet['author']['id']] : 0;
                    }
                    foreach ($sheet['sheets'] as $key=>$val) {
                        $scoreSheetList[] = array(
                            "sheet_id"  => $sheetMap[$val['sid']],
                            "score_id"  => $scoreMap[$sheet['score_oid']],
                            "index"     => $val['index'],
                            "creator"=>$creator
                        );
                    }
                    
                }

                
                $Model = M('ScoreSheet');
                $count = count($scoreSheetList);
                $start = 0;
                while($start <= $count) {
                    $slice_data = array_slice($scoreSheetList, $start, 50);
                    $rowCount = $Model->addAll($slice_data);
                    $start += 50;
                    echo $Model->getDbError();
                }
            }
        }
        

        fclose($file);
    }

    private function process_newlist(){
        return;
    }
    
    private function process_score($filePath){
        Log::writeInfo('start to process_score in DataTransferProvider, param:' .$filePath,'data_transfer');
        $file = fopen($filePath, 'r');
        $data = array();
        
        $user = array();
        $admin = array();
        $images = array();
        $tags = array();
        
        while(!feof($file)) {
            
            $json = fgets($file);
            $obj = json_decode($json, true);
            //print_r($obj);
            if(empty($obj)) continue;
            if($obj['state'] == 'checking' ){
                $state = 0;
            }elseif ($obj['state'] == 'fail') {
                $state = 20;
            }else{
                $state = 10;
            }
            
            if($obj['author']['author_type'] == 'admin') {
                $admin[] = array(
                    'oid'   =>  $obj['_id']['$oid'],
                    'admin_id' => $obj['author']['id'],
                );
            } else {
                $user[] = array(
                    'oid'   =>  $obj['_id']['$oid'],
                    'user_id' => $obj['author']['id'],
                );
            }
            
            $data[] = array(
                'oid'  =>  $obj['_id']['$oid'],
                'name'  =>  $obj['name'],
                'status'  => $state,
                'song_name'  => $obj['s_name'],
                'singer'  => $obj['singer'],
                'author'   => $obj['author'],
                'author_type'  => $obj['author']['author_type'] == 'admin' ? 10: 20,
                'desc'  => $obj['description'],
                'create_time'  =>  date("Y-m-d H:i:s",strtotime($obj['create_date']['$date'])),
            );
            
            $pic =array(
                "pic"=>$obj['pic'],
                "sheet_oid"  =>  $obj['_id']['$oid'],
                'author_type'  => $obj['author']['author_type'] == 'admin' ? 10: 20,
                "author"=>$obj['author']
            ) ;
            $picList[] = $pic;
            
            $tags[] = array(
                "tags"=>$obj['tags'],
                "sheet_oid"  =>  $obj['_id']['$oid'],
                'author_type'  => $obj['author']['author_type'] == 'admin' ? 10: 20,
                "author"=>$obj['author']
            );

            if(count($data) % 50 == 0) {
                Log::writeInfo('start to batch_insert_score in DataTransferProvider, data.size:'.count($data),'data_transfer');
                $this->batch_insert_score($data, $images, $picList, $user, $admin ,$tags);
                unset($data);
                unset($images);
                unset($picList);
                unset($user);
                unset($admin);
                unset($tags);
            }

        }
        
        if(!empty($data)) $this->batch_insert_score($data, $images, $picList, $user, $admin ,$tags);
        
        fclose($file);
    }

    private function batch_insert_score($data, $images, $picList, $user, $admin ,$tags ){
        //获取admin 和user信息
        $admin_oids = array_unique(array_column($admin, "admin_id"));
        $map['oid'] = array('in', $admin_oids);
        $Model = M('Member');
        $adminList = $Model->where($map)->select();   
        $adminMap = array();
        foreach ($adminList as $key=> $val) {
            $adminMap[$val['oid']]  = $val['uid'];
        }

        unset($map);
        $user_oids = array_unique(array_column($user, "user_id"));
        if(!empty($user_oids)) {
            $map['oid'] = array('in', $user_oids);
            $userList = M('User')->where($map)->select();
            $userMap = array();
            foreach ($adminList as $key=> $val) {
                $userMap[$val['oid']]  = $val['id'];
            }
        }
        foreach ($data as $key=>$sheet) {
            //admin
            if($sheet['author_type'] == 10) {
                $data[$key]['creator'] = $adminMap[$sheet['author']['id']];
            } else {
                $data[$key]['creator'] = isset($userMap) ? $userMap[$sheet['author']['id']] : 0;
            }
            unset($data[$key]['author']);
        }
        

        //分批添加曲谱
        $Model = M('Sheet');
        $count = count($data);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($data, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 100;
            echo $Model->getDbError();
        }
        
        
        //添加谱曲图片信息
        foreach ($picList as $key=>$pic) {
            if($pic['author_type'] == 10) {
                $creator = $adminMap[$pic['author']['id']];
            } else {
                $creator = isset($userMap) ? $userMap[$pic['author']['id']] : 0;
            }
            foreach ($pic['pic'] as $key=>$val) {
                $images[] = array(
                    "name"  => $val['name'],
                    "url"  => $val['thumbUrl'],
                    "img_type"  => 10,
                    "creator"=>$creator,
                    "oid"   => $val['_id']['$oid']
                    
                );
            }
        }
        
        Log::writeInfo('start to batch_insert_image in DataTransferProvider, images.size:'.count($images),'data_transfer');
        $Model = M('Image');
        $count = count($images);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($images, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 50;
            echo $Model->getDbError();
        }
        
        //图片和曲谱的关系
        unset($map);
        $sheet_oids = array_column($picList, "sheet_oid");
        $map['oid'] = array('in', $sheet_oids);
        $sheetList = M('Sheet')->where($map)->select();
        
        foreach ($sheetList as $key=> $val) {
            $sheetMap[$val['oid']]  = $val['id'];
        }
        
        unset($map);
        $image_oids = array_column($images, "oid");
        $map['oid'] = array('in', $image_oids);
        $imageList = M('Image')->where($map)->select();
        foreach ($imageList as $key=> $val) {
            $imageMap[$val['oid']]  = $val['id'];
        }
        
        $image_sheet = array();
        foreach ($picList as $key=>$pic) {
            if($pic['author_type'] == 10) {
                $creator = $adminMap[$pic['author']['id']];
            } else {
                $creator = isset($userMap) ? $userMap[$pic['author']['id']] : 0;
            }
            foreach ($pic['pic'] as $key=>$val) {
                $image_sheet[] = array(
                    'sheet_id' => $sheetMap[$pic['sheet_oid']],
                    'image_id' => $imageMap[$val['_id']['$oid']],
                    'creator'  => $creator
                );
            }
            
        }
        
        Log::writeInfo('start to batch_insert_image_sheet in DataTransferProvider, image_sheet.size:'.count($image_sheet),'data_transfer');
        $Model = M('ImageSheet');
        $count = count($image_sheet);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($image_sheet, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 50;
            echo $Model->getDbError();
        }
        
        //添加谱曲和标签关系
        unset($map);
         $tag_oids = array();
        foreach ($tags as $key => $tag) {
            $tag_oids =  array_merge($tag['tags'], $tag_oids);
            
        }
        
        if(!empty($tag_oids)) {
            $map['oid'] = array('in', array_unique($tag_oids));
            $Model = M('Tag');
            $tagsList = $Model->where($map)->select();
            foreach ($tagsList as $key=> $val) {
                $tagMap[$val['oid']]  = $val['id'];
            }

            $tagSheetList = array();
            foreach ($tags as $key=>$tag) {
                if($tag['author_type'] == 10) {
                    $creator = $adminMap[$tag['author']['id']];
                } else {
                    $creator = isset($userMap) ? $userMap[$tag['author']['id']] : 0;
                }
                foreach ($tag['tags'] as $key=>$val) {
                    $tagSheetList[] = array(
                        "tag_id"  => $tagMap[$val],
                        "sheet_id"  => $sheetMap[$tag['sheet_oid']],
                        "creator"=>$creator
                    );
                }
                
            }
            
            Log::writeInfo('start to batch_insert_tag_sheet in DataTransferProvider, tag_sheet.size:'.count($image_sheet),'data_transfer');
            $Model = M('TagSheet');
            $count = count($tagSheetList);
            $start = 0;
            while($start <= $count) {
                $slice_data = array_slice($tagSheetList, $start, 50);
                $rowCount = $Model->addAll($slice_data);
                $start += 50;
                echo $Model->getDbError();
            }
        }
    }
    
    private function process_tag($filePath){
        $file = fopen($filePath, 'r');
        $data = array();
        while(!feof($file)) {
            
            $json = fgets($file);
            $obj = json_decode($json, true);
            //print_r($obj);
            if(empty($obj)) continue;
            if($obj['tType'] == 'score' ){
                $type = 3;
            }elseif ($obj['tType'] == 'list') {
                $type = 2;
            }else{
                $type = 1;
            }
            $data[] = array(
                'oid'  =>  $obj['_id']['$oid'],
                'name'  =>  $obj['name'],
                'type'  => $type,
                'create_time'  =>  date("Y-m-d H:i:s",strtotime($obj['create_date']['$date'])),
            );
        }
        
        //分批入库
        $Model = M('Tag');
        $count = count($data);
        $start = 0;
        while($start <= $count) {
            $slice_data = array_slice($data, $start, 50);
            $rowCount = $Model->addAll($slice_data);
            $start += 50;
            echo $Model->getDbError();
        }
        fclose($file);
    }
    
    private function process_user($filePath){
        
        $file = fopen($filePath, 'r');
        $users = array();
        while(!feof($file)) {
            
            $json = fgets($file);
            $obj = json_decode($json, true);
            //print_r($obj);
            if(empty($obj)) continue;
            $users[] = array(
                'oid'  =>  $obj['_id']['$oid'],
                'nick_name'  =>  $obj['name'],
                'openid'  =>  $obj['openid'],
                'img'  =>  $obj['img'],
                'create_time'  =>  date("Y-m-d H:i:s",strtotime($obj['create_date']['$date'])),
                'update_time'  =>  date("Y-m-d H:i:s",strtotime($obj['update_date']['$date'])),
            );
        }
        
        //分批入库
        $Model = M('User');
        $count = count($users);
        $start = 0;
        while($start <= $count) {
            $data = array_slice($users, $start, 50);
            $rowCount = $Model->addAll($data);
            $start += 50;
            echo $Model->getDbError();
        }
        fclose($file);
    }
}
